//
//  YJRegistView.m
//  YJB
//
//  Created by 中电大维 on 16/5/12.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "YJRegistView.h"
#import "YJNetworkTool.h"
#import "Masonry.h"

@interface YJRegistView ()
@property(nonatomic,strong)NSMutableArray<UITextField *> *textFields;
@property(nonatomic,strong)UIButton    *registBtn;
@property(nonatomic,strong)UIButton    *userProtocolBtn;
@property(nonatomic,strong)UIButton    *choiceProtocolBtn;

@end
@implementation YJRegistView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.textFields = [NSMutableArray array];
        [self createInputTextFiled];
        self.registBtn.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (UIButton *)userProtocolBtn
{
    if (_userProtocolBtn == nil)
    {
        _userProtocolBtn = [[UIButton alloc] init];
        [_userProtocolBtn setTitle:@"我已看过并接受《用户协议》" forState:UIControlStateNormal];
        _userProtocolBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        _userProtocolBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_userProtocolBtn setTitleColor:kUIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [self addSubview:_userProtocolBtn];
        [_userProtocolBtn mas_makeConstraints:^(MASConstraintMaker *make)
         {
             make.left.mas_equalTo(self.choiceProtocolBtn.mas_right).offset(10);
             make.width.mas_equalTo(180);
             make.centerY.mas_equalTo(self.choiceProtocolBtn.mas_centerY);
             make.height.mas_equalTo(20);
         }];
    }
    return _userProtocolBtn;
}

- (UIButton *)choiceProtocolBtn
{
    if (_choiceProtocolBtn == nil)
    {
        _choiceProtocolBtn = [[UIButton alloc] init];
        [_choiceProtocolBtn setImage:Image(@"add_check_normal") forState:UIControlStateNormal];
        [_choiceProtocolBtn setImage:Image(@"add_check_select") forState:UIControlStateSelected];
        _choiceProtocolBtn.selected = YES;
        [_choiceProtocolBtn addTarget:self action:@selector(choiceProtocolBtnTaped) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_choiceProtocolBtn];
        UITextField *lastTextField = _textFields.lastObject;
        [_choiceProtocolBtn mas_makeConstraints:^(MASConstraintMaker *make)
         {
             make.left.mas_equalTo(17);
             make.width.mas_equalTo(25);
             make.top.mas_equalTo(lastTextField.mas_bottom).offset(15);
             make.height.mas_equalTo(25);
         }];
    }
    return _choiceProtocolBtn;
}

- (UIButton *)registBtn
{
    if (_registBtn == nil)
    {
        _registBtn = [[UIButton alloc]init];
        [_registBtn setBackgroundImage:Image(@"button_icon") forState:UIControlStateNormal];
        [_registBtn setBackgroundImage:Image(@"button_icon_HL") forState:UIControlStateHighlighted];
        [_registBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registBtn addTarget:self action:@selector(registClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_registBtn];
        [_registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(17.5);
            make.right.mas_equalTo(-17.5);
            make.height.mas_equalTo(45);
            make.top.mas_equalTo(self.userProtocolBtn).offset(30);
        }];
    }
    return _registBtn;
}

- (void)choiceProtocolBtnTaped
{
    _choiceProtocolBtn.selected = !_choiceProtocolBtn.selected;
    self.registBtn.enabled = !self.registBtn.enabled;
    
}

- (void)createInputTextFiled
{
    NSArray *placeholders = @[@"用户名",@"Email",@"密 码",@"确认密码: ",@"推广码(链接)"];
    UITextField *lastTextField = nil;
    for (int i = 0; i < placeholders.count; i ++)
    {
        UITextField *textField = [[UITextField alloc]init];
        textField.font = FONT(16);
        textField.clearButtonMode = UITextFieldViewModeAlways;
        textField.placeholder = placeholders[i];
        textField.background = Image(@"login_inputView_bg");
        if (i == 1)
            textField.keyboardType = UIKeyboardTypeEmailAddress;
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 10;
        textField.leftView = leftView;
        textField.leftViewMode = UITextFieldViewModeAlways;
        [self addSubview:textField];
        [self.textFields addObject:textField];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(17.5);
            make.right.mas_equalTo(-17.5);
            make.height.mas_equalTo(44);
            if (lastTextField)
                make.top.mas_equalTo(lastTextField.mas_bottom).offset(12);
            else
                make.top.mas_equalTo(15);
        }];
        lastTextField = textField;
        if (i == 2 || i == 3)
            textField.secureTextEntry = YES;
    }
}

- (void)registClick:(UIButton *)sender
{
        [self endEditing:YES];
        NSArray *messages = @[@"请输入用户名",@"请输入Email",@"请输入密码",@"请输入确认密码"];
        int i;
        for (i = 0; i < messages.count; i ++)
        {
            UITextField *textFiel = self.textFields[i];
            if (textFiel.text.length == 0)
            {
                [MBProgressHUD showError:messages[i]];
                return;
            }
        }
        
        UITextField *useName = self.textFields[0];
        UITextField *email = self.textFields[1];
        UITextField *passWord = self.textFields[2];
        UITextField *againPassWord = self.textFields[3];
        UITextField *pushCode = self.textFields[4];
    
        //检测密码一致性
        if (![passWord.text isEqualToString:againPassWord.text])
        {
            [MBProgressHUD showError:@"两次输入密码不一致"];
            return;
        }
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSString *mdStr = [[[@"admin" stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key]md5];
        param[@"action"] = @"register";
        param[@"makegold"] = @{ @"username":useName.text,
                                @"password":[passWord.text md5],
                                @"email":email.text,
                                @"mobile_phone":self.telStr,
                                @"reffercode":pushCode.text.length?pushCode.text:@"AAAAA",
                                @"user_info":@"admin",
                                @"phone_info":@"iOS",
                                @"md5_key":mdStr};

        [YJNetworkTool postWithUrl:NEWURL(@"user.php") parameters:param success:^(id responseObject) {
            NSString *code = responseObject[@"return"][@"code"];
            if (code.integerValue == 200)
            {
                [MBProgressHUD hideHUD];
                //发出通知，更新登录框中的用户名和密码
                [NOTIFICATIONCENTER postNotificationName:YJUserDidSuccessRegistNotification object:nil userInfo:@{@"userName":useName.text,@"pasword":passWord.text}];
                [MBProgressHUD showSuccess:@"注册成功"];
            }else
            {   [MBProgressHUD hideHUD];
                [MBProgressHUD showError:responseObject[@"return"][@"message"]];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"网络不佳，稍后重试"];
        }];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}

-(void)dealloc
{
    [NOTIFICATIONCENTER removeObserver:self];
}
@end
